package com.jthinker.base.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by chen.gang on 2014/11/8.
 */
public class CacheUtils
{
    private static final Logger LOGGER = LoggerFactory.getLogger(CacheUtils.class);

    private static final CacheManager CACHE_MANAGER = CacheManager.newInstance(CacheUtils.class.getResourceAsStream("/ehcache.xml"));

    public static <T> T add(String cacheName, Object key, T value)
    {
        Cache cache = CACHE_MANAGER.getCache(cacheName);

        Element element = new Element(key, value);
        Element prev = cache.putIfAbsent(element);

        if (prev != null)
        {
            return (T) prev.getObjectValue();
        }

        return null;
    }

    public static <T> T get(String cacheName, Object key)
    {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        LOGGER.info("cache name {} \n{}", cacheName, cache.getKeys());
        Element element = cache.get(key);
        return element != null ? (T) element.getObjectValue() : null;
    }

    public static boolean remove(String cacheName, Object key)
    {
        Cache cache = CACHE_MANAGER.getCache(cacheName);
        return cache.remove(key);
    }
}
